package com.example.mydy.utils;

import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.OpenableColumns;
import android.util.Log;
import android.widget.ImageView;

import com.example.mydy.R;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 图片处理工具类
 */
public class ImageUtils {
    private static final String TAG = "ImageUtils";
    private static final String AVATAR_DIR = "avatars";
    private static final int MAX_IMAGE_SIZE = 800; // 最大图片尺寸
    private static final int QUALITY = 85; // JPEG压缩质量

    /**
     * 保存用户头像
     * @param context 上下文
     * @param bitmap 头像位图
     * @param username 用户名，用于生成唯一文件名
     * @return 保存的头像路径，失败返回null
     */
    public static String saveUserAvatar(Context context, Bitmap bitmap, String username) {
        if (bitmap == null || username == null || username.isEmpty()) {
            Log.e(TAG, "Invalid parameters for saving avatar");
            return null;
        }

        // 创建存储目录
        File avatarDir = new File(context.getFilesDir(), AVATAR_DIR);
        if (!avatarDir.exists()) {
            if (!avatarDir.mkdirs()) {
                Log.e(TAG, "Failed to create avatar directory");
                return null;
            }
        }

        // 创建唯一文件名
        String fileName = "avatar_" + username + ".jpg";
        File avatarFile = new File(avatarDir, fileName);

        try {
            // 压缩并保存图片
            Bitmap compressedBitmap = compressBitmap(bitmap, MAX_IMAGE_SIZE);
            FileOutputStream fos = new FileOutputStream(avatarFile);
            compressedBitmap.compress(Bitmap.CompressFormat.JPEG, QUALITY, fos);
            fos.flush();
            fos.close();

            if (compressedBitmap != bitmap) {
                compressedBitmap.recycle();
            }

            return avatarFile.getAbsolutePath();
        } catch (IOException e) {
            Log.e(TAG, "Error saving avatar: " + e.getMessage());
            return null;
        }
    }

    /**
     * 压缩位图到指定最大尺寸
     * @param bitmap 原始位图
     * @param maxSize 最大尺寸（宽或高）
     * @return 压缩后的位图
     */
    private static Bitmap compressBitmap(Bitmap bitmap, int maxSize) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();

        // 如果图片已经小于最大尺寸，直接返回
        if (width <= maxSize && height <= maxSize) {
            return bitmap;
        }

        // 计算缩放比例
        float scale;
        if (width > height) {
            scale = (float) maxSize / width;
        } else {
            scale = (float) maxSize / height;
        }

        // 缩放图片
        int newWidth = Math.round(width * scale);
        int newHeight = Math.round(height * scale);
        return Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true);
    }

    /**
     * 从Uri加载位图
     * @param context 上下文
     * @param imageUri 图片Uri
     * @return 加载的位图，失败返回null
     */
    public static Bitmap loadBitmapFromUri(Context context, Uri imageUri) {
        try {
            InputStream inputStream = context.getContentResolver().openInputStream(imageUri);
            // 获取图片的原始尺寸
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(inputStream, null, options);
            inputStream.close();

            // 重新打开输入流
            inputStream = context.getContentResolver().openInputStream(imageUri);
            
            // 计算合适的缩放比例
            options.inJustDecodeBounds = false;
            options.inSampleSize = calculateInSampleSize(options, MAX_IMAGE_SIZE, MAX_IMAGE_SIZE);
            
            // 解码图片
            Bitmap bitmap = BitmapFactory.decodeStream(inputStream, null, options);
            inputStream.close();
            return bitmap;
        } catch (Exception e) {
            Log.e(TAG, "Error loading bitmap from uri: " + e.getMessage());
            return null;
        }
    }

    /**
     * 计算图片缩放比例
     */
    private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        int height = options.outHeight;
        int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {
            final int halfHeight = height / 2;
            final int halfWidth = width / 2;

            while ((halfHeight / inSampleSize) >= reqHeight && (halfWidth / inSampleSize) >= reqWidth) {
                inSampleSize *= 2;
            }
        }

        return inSampleSize;
    }

    /**
     * 从文件路径加载头像到ImageView
     * @param context 上下文
     * @param imageView 目标ImageView
     * @param filePath 头像文件路径
     */
    public static void loadAvatarIntoImageView(Context context, ImageView imageView, String filePath) {
        if (filePath == null || filePath.isEmpty()) {
            // 加载默认头像
            imageView.setImageResource(R.drawable.default_avatar);
            return;
        }

        try {
            File file = new File(filePath);
            if (!file.exists()) {
                imageView.setImageResource(R.drawable.default_avatar);
                return;
            }

            // 加载图片
            Bitmap bitmap = BitmapFactory.decodeFile(filePath);
            if (bitmap == null) {
                imageView.setImageResource(R.drawable.default_avatar);
            } else {
                imageView.setImageBitmap(bitmap);
            }
        } catch (Exception e) {
            Log.e(TAG, "Error loading avatar: " + e.getMessage());
            imageView.setImageResource(R.drawable.default_avatar);
        }
    }

    /**
     * 获取用户头像文件路径
     * @param context 上下文
     * @param username 用户名
     * @return 头像文件路径，如果不存在返回null
     */
    public static String getUserAvatarPath(Context context, String username) {
        if (username == null || username.isEmpty()) {
            return null;
        }

        File avatarDir = new File(context.getFilesDir(), AVATAR_DIR);
        String fileName = "avatar_" + username + ".jpg";
        File avatarFile = new File(avatarDir, fileName);

        if (avatarFile.exists()) {
            return avatarFile.getAbsolutePath();
        }
        return null;
    }

    /**
     * 删除用户头像
     * @param context 上下文
     * @param username 用户名
     * @return 是否删除成功
     */
    public static boolean deleteUserAvatar(Context context, String username) {
        String avatarPath = getUserAvatarPath(context, username);
        if (avatarPath != null) {
            File file = new File(avatarPath);
            return file.delete();
        }
        return false;
    }

    public static File compressAndSaveImage(Context context, Uri imageUri) throws IOException {
        Bitmap bitmap = getBitmapFromUri(context, imageUri);
        if (bitmap == null) return null;

        // 压缩图片
        bitmap = compressImage(bitmap);

        // 保存到缓存目录
        return saveBitmapToFile(context, bitmap);
    }

    private static Bitmap getBitmapFromUri(Context context, Uri uri) throws IOException {
        InputStream inputStream = context.getContentResolver().openInputStream(uri);
        if (inputStream == null) return null;

        Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
        inputStream.close();
        return bitmap;
    }

    private static Bitmap compressImage(Bitmap bitmap) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        float scale = 1.0f;

        // 如果图片尺寸超过限制，进行缩放
        if (width > MAX_IMAGE_SIZE || height > MAX_IMAGE_SIZE) {
            if (width > height) {
                scale = (float) MAX_IMAGE_SIZE / width;
            } else {
                scale = (float) MAX_IMAGE_SIZE / height;
            }
            width = Math.round(width * scale);
            height = Math.round(height * scale);
            Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, width, height, true);
            bitmap.recycle();
            bitmap = scaledBitmap;
        }

        return bitmap;
    }

    private static File saveBitmapToFile(Context context, Bitmap bitmap) throws IOException {
        // 创建缓存目录
        File cacheDir = context.getCacheDir();
        if (!cacheDir.exists()) {
            cacheDir.mkdirs();
        }

        // 生成文件名
        String fileName = "compressed_image_" + System.currentTimeMillis() + ".jpg";
        File file = new File(cacheDir, fileName);

        // 保存图片
        FileOutputStream fos = new FileOutputStream(file);
        bitmap.compress(Bitmap.CompressFormat.JPEG, QUALITY, fos);
        fos.close();

        return file;
    }

    public static void clearImageCache(Context context) {
        File cacheDir = context.getCacheDir();
        if (cacheDir.exists()) {
            File[] files = cacheDir.listFiles();
            if (files != null) {
                for (File file : files) {
                    if (file.getName().startsWith("compressed_image_")) {
                        file.delete();
                    }
                }
            }
        }
    }

    public static File getImageFile(Context context, String fileName) {
        File cacheDir = context.getCacheDir();
        return new File(cacheDir, fileName);
    }
    
    /**
     * 从Uri获取文件名
     * @param context 上下文
     * @param uri 文件Uri
     * @return 文件名
     */
    public static String getFileNameFromUri(Context context, Uri uri) {
        String result = null;
        if (uri.getScheme().equals("content")) {
            try (Cursor cursor = context.getContentResolver().query(uri, null, null, null, null)) {
                if (cursor != null && cursor.moveToFirst()) {
                    int nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
                    if (nameIndex != -1) {
                        result = cursor.getString(nameIndex);
                    }
                }
            } catch (Exception e) {
                Log.e(TAG, "获取文件名失败: " + e.getMessage());
            }
        }
        if (result == null) {
            result = uri.getPath();
            int cut = result.lastIndexOf('/');
            if (cut != -1) {
                result = result.substring(cut + 1);
            }
        }
        return result;
    }
    
    /**
     * 从Uri获取文件
     * @param context 上下文
     * @param uri 文件的Uri
     * @return 文件对象，如果获取失败则返回null
     */
    public static File getFileFromUri(Context context, Uri uri) {
        if (uri == null) return null;
        
        try {
            // 先尝试通过路径获取
            if ("file".equals(uri.getScheme())) {
                return new File(uri.getPath());
            }
            
            // 如果是content类型，复制到缓存文件
            InputStream inputStream = context.getContentResolver().openInputStream(uri);
            if (inputStream == null) return null;
            
            // 创建临时文件
            String fileName = getFileNameFromUri(context, uri);
            File cacheDir = context.getCacheDir();
            File tempFile = new File(cacheDir, "task_image_" + System.currentTimeMillis() + 
                    (fileName.endsWith(".jpg") ? "" : ".jpg"));
            
            // 复制数据
            FileOutputStream outputStream = new FileOutputStream(tempFile);
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            outputStream.close();
            inputStream.close();
            
            return tempFile;
        } catch (Exception e) {
            Log.e(TAG, "获取文件失败", e);
            return null;
        }
    }

    /**
     * 将图片数据保存到内部存储，并返回保存路径
     * @param context 上下文
     * @param imageData 图片数据
     * @param fileName 文件名
     * @return 保存的路径，失败返回null
     */
    public static String saveImageToInternalStorage(Context context, byte[] imageData, String fileName) {
        File directory = new File(context.getFilesDir(), "task_images");
        if (!directory.exists()) {
            if (!directory.mkdirs()) {
                Log.e(TAG, "创建目录失败");
                return null;
            }
        }

        String filePath = directory.getAbsolutePath() + File.separator + fileName + ".jpg";
        File file = new File(filePath);

        try (FileOutputStream fos = new FileOutputStream(file)) {
            fos.write(imageData);
            fos.flush();
            return filePath;
        } catch (IOException e) {
            Log.e(TAG, "保存图片失败: " + e.getMessage());
            return null;
        }
    }

    /**
     * 根据路径加载图片
     * @param imagePath 图片路径
     * @return Bitmap对象，失败返回null
     */
    public static Bitmap loadImageFromPath(String imagePath) {
        if (imagePath == null || imagePath.isEmpty()) {
            return null;
        }

        try {
            return BitmapFactory.decodeFile(imagePath);
        } catch (Exception e) {
            Log.e(TAG, "加载图片失败: " + e.getMessage());
            return null;
        }
    }
    
    /**
     * 从内部存储加载图片
     * @param context 上下文
     * @param imagePath 图片相对路径或绝对路径
     * @return Bitmap对象，失败返回null
     */
    public static Bitmap loadImageFromStorage(Context context, String imagePath) {
        if (imagePath == null || imagePath.isEmpty()) {
            return null;
        }

        try {
            // 如果是绝对路径，直接加载
            if (imagePath.startsWith("/")) {
                return BitmapFactory.decodeFile(imagePath);
            }
            
            // 如果是相对路径，从内部存储加载
            File directory = new File(context.getFilesDir(), "task_images");
            File file = new File(directory, imagePath);
            if (file.exists()) {
                return BitmapFactory.decodeFile(file.getAbsolutePath());
            }
            
            // 文件不存在
            return null;
        } catch (Exception e) {
            Log.e(TAG, "从内部存储加载图片失败: " + e.getMessage());
            return null;
        }
    }
} 